package com.lfy.auth.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lfy.auth.domain.entity.UserDetailEntity;
import com.lfy.auth.domain.entity.UserEntity;
import com.lfy.auth.domain.msg.RemoveFileMsg;
import com.lfy.auth.service.FileService;
import com.lfy.auth.service.UserDetailService;
import com.lfy.common.constant.DefaultUserConstant;
import com.lfy.common.enums.BaseEnum;
import com.lfy.common.result.R;
import com.lfy.commons.utils.MinioUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private UserDetailService userDetailService;
    @Value("${headImgPrefix}")
    public String headPrefix;
    @Resource
    private ApplicationEventPublisher publisher;


    @Override
    public R<String> up(UserEntity user, MultipartFile file) {
        String fIleName = user.getId().toString().concat(DigestUtil.md5Hex(file.getOriginalFilename()));
        String imgName = minioUtil.upload(file, fIleName);
        if(Objects.isNull(imgName)){
            return R.error(BaseEnum.commonEnum.SYSTEM_ERROR);
        }
        UserDetailEntity userDetail = this.userDetailService.getOne(new LambdaQueryWrapper<UserDetailEntity>().eq(UserDetailEntity::getUserId, user.getId()));
        String headImg = headPrefix.concat("/").concat(imgName);
        UserDetailEntity userDetailEntity = new UserDetailEntity();
        userDetailEntity.setImg(headImg);
        userDetailService.update(userDetailEntity,new LambdaQueryWrapper<UserDetailEntity>().eq(UserDetailEntity::getUserId,user.getId()));

        if(!userDetail.getImg().equals(DefaultUserConstant.DEFAULT_HEAD_IMG)){
            //删除旧头像文件
            publisher.publishEvent(new RemoveFileMsg(this,fIleName));
        }

        return R.success(headImg);
    }


}
